export function getFileBySrcTest(src) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', src);
    xhr.responseType = 'blob';
    xhr.onload = function (e) {
        if (this.status == 200) {
            var blob = e.target.response;
            console.log(blob);
        }
    }
}

// 通过src获取file对象
function getFileBySrc(file, src, i, obj, DEntry2) {
    // var xhr = new XMLHttpRequest();
    // xhr.open('GET', src);
    // xhr.responseType = 'blob';
    // xhr.onload = function(e) {
    //     if (this.status == 200) {
    //         console.log('请求本地照片文件成功');
    //         console.dir(e.target);
    //         var blob = e.target.response;
    //         file.createWriter(function(writer){
    //             var blobBuilder = new BlobBuilder();
    //             blobBuilder.append(blob);
    //             writer.write(blobBuilder.getBlob('image/*'));
    //             writer.onwriteend = function() {
    //                 console.log('img写入成功');
    //                 console.log('Write completed.');
    //                 Iteration1(i + 1, obj, DEntry2);
    //             };
    //         },function(){
    //             console.log('写入失败');
    //         });
    //     }
    // };
    // xhr.send();
}

function Iteration(i, list, DEntry1, basePath, endCallBack) {
    if (i >= list.length) {
        if (endCallBack) {
            endCallBack();
        }
        return;
    }
    let obj = list[i];
    DEntry1.getDirectory(obj.label, { create: true }, function () {
        if (obj.list && obj.list.length > 0) {
            Iteration1(0, obj, basePath);
        }
        Iteration(i + 1, list, DEntry1, basePath, endCallBack);
    }, function (err) {
        console.log(err);
    });
}
function Iteration1(i, obj, path, endCallBack) {
    if (i >= obj.list.length) {
        if (endCallBack) {
            endCallBack();
        }
        return;
    }
    let obj1 = obj.list[i];
    const mimeObj = {
        'image/x-ms-bmp': '.bmp',
        'image/jpeg': '.jpg',
        'image/gif': '.gif',
        'image/png': '.png',
        'image/tiff': '.tiff',
        'image/x-targa': '.tga',
        'image/vnd.adobe.photoshop': '.psd'
    }
    var base64 = localStorage.getItem(obj1.item);
    let arr = base64.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let filePath = path + '/' + obj.label + '/' + obj.label + '-' + i + mimeObj[mime];
    var bitmap = new plus.nativeObj.Bitmap("test");
    bitmap.loadBase64Data(base64,function(){
        bitmap.save(filePath,{overwrite:true,quality:20},function(file){
            // console.log('保存图片成功')
            Iteration1(i + 1, obj, path);
        });
    },function(){
        console.log('加载图片失败')
    })
    // 大坑，FileReader不能够写入图片文件，只支持文本文件
    // DEntry2.getFile(fileName, { create: true }, function (file) {
    //     console.log('创建一级分类-描述照片-jpg文件成功');
    //     var reader=new FileReader();
    //     reader.readAsText(fileObj);
    //     reader.onload=function(){
    //         var result = this.result;
    //         file.createWriter(function (writer) {
    //             writer.onwriteend = function () {
    //                 console.log('写入成功');
    //                 Iteration1(i + 1, obj, DEntry2);
    //             };
    //             writer.onerror = function (e) {
    //                 console.log('Write failed: ' + e.toString());
    //             };
    //             writer.write(result);
    //         });
    //     }
    // }, function (err) {
    //     console.log(err);
    // });
}

function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}
function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

export function tranObjToZip(obj, cb) {
    console.log(JSON.stringify(obj));
    plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function (fs) {
        // 创建项目文件夹
        fs.root.getDirectory('_doc/' + obj.assetsName, { create: true }, function (DEntry) {
            var endCallBack = function(obj, cb) {
                const targetPath = '_doc/' + obj.assetsName + '/';
                const zipfile = '_doc/' + obj.assetsName + '.zip';
                plus.zip.compress(targetPath,zipfile,function() {  
                    console.log('文件生成完毕');
                    if (cb) {
                        cb();
                    } 
                },function(err) {  
                    console.log(err); 
                });
            }
            // 创建一级分类文件夹
            DEntry.getDirectory(obj.level1, { create: true }, function (DEntry1) {
                if (obj.photo && obj.photo.length > 0) {
                    const pathName = '_doc/' + obj.assetsName + '/' + obj.level1;
                    if (obj.level2list && obj.level2list.length > 0) {
                        Iteration(0, obj.photo, DEntry1, pathName);
                    } else {
                        Iteration(0, obj.photo, DEntry1, pathName, () => {
                            endCallBack(obj, cb);
                        });
                    }
                }
            });
            // 循环遍历创建二级分类文件夹
            createLevel2(0, obj, DEntry, () => {
                endCallBack(obj, cb);
            });
        }, function (err) {
            console.log(err);
        });
    }, function (err) {
        console.log(err);
    });
}

function createLevel2(i, obj1, DEntry, endCallBack) {
    if (i >= obj1.level2list.length) {
        if (endCallBack) {
            endCallBack();
        }
        return;
    }
    let obj = obj1.level2list[i] || {};
    DEntry.getDirectory(obj.label, { create: true }, function (DEntry1) {
        if (obj.photo && obj.photo.length > 0) {
            const pathName = '_doc/' + obj1.assetsName + '/' + obj.label;
            Iteration(0, obj.photo, DEntry1, pathName, () => {
                createLevel2(i + 1, obj1, DEntry, endCallBack);
            });
        } else {
            createLevel2(i + 1, obj1, DEntry, endCallBack);
        }
    });
}

export function compressImageCanvas(base64, callback) {
    var img = new Image();
    img.src = base64;
    console.log(img);
    img.onload = function () {
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        // 图片原始尺寸
        var originWidth = this.width;
        var originHeight = this.height;
        var maxWidth = 1000;
        var targetWidth = originWidth;
        var targetHeight = originHeight;
        if (originWidth > maxWidth) {
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
        }
        // canvas对图片进行缩放
        canvas.width = targetWidth;
        canvas.height = targetHeight;
        // 清除画布
        context.clearRect(0, 0, targetWidth, targetHeight);
        // 图片压缩
        context.drawImage(img, 0, 0, targetWidth, targetHeight);
        var newUrl = canvas.toDataURL('image/jpeg', 0.7);
        if (callback) {
            callback(newUrl);
        }
    }
}

// 有点问题 ，下次不做兼容就ok了
function downLoadFile(src) {
    let aLink = document.createElement('a');
    let blob = dataURLtoBlob(src); //new Blob([content]);
    let evt = document.createEvent("HTMLEvents");
    evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
    aLink.download = '111.jpg';
    aLink.href = URL.createObjectURL(blob);
    // aLink.dispatchEvent(evt);
    //aLink.click()
    aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐
}